'use strict';

const extend = require('util')._extend;

const through = require('through2');
const ext = require('gulp-util').replaceExtension;
const jade = require('virtual-jade');
const PluginError = require('gulp-util').PluginError;

module.exports = function(options){
    const opts = extend({}, options);

    function CompileJade(file, enc, cb){

        opts.filename = file.path;

        if(file.data){
            opts.data = file.data;
        }

        file.path = ext(file.path, '.js');

        if(file.isStream()){
            return cb(new PluginError('virtual-jade', 'Streaming not supported'));
        }

        if(file.isBuffer()){
            try {
                let contents = String(file.contents);
                let compiled = jade(contents, opts);
                file.contents = new Buffer(compiled);
            } catch(e) {
                return cb(new PluginError('virtual-jade', e));
            }
        }
        cb(null, file);
    }

    return through.obj(CompileJade);
};
